package com.zy.config;

import com.zy.service.PermissionService;
import com.zy.service.UserService;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;


@Configuration
public class ShiroConfig {
    @Resource
    private UserService userService;
    @Resource
    private PermissionService permissionService;
    //securitymanager
    @Bean
    public SecurityManager securityManager(){
        DefaultWebSecurityManager securityManager= new DefaultWebSecurityManager();
        //指向realm
        securityManager.setRealm(smbmsRealm());
        return securityManager;
    }
    //shirofilter 过滤器  入口类
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //指向securitymanager
        shiroFilterFactoryBean.setSecurityManager(securityManager());
        Map<String,String> filterchains = new HashMap<>();
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterchains);
        filterchains.put("/logout1","logout");//退出默认的路径    /
        filterchains.put("/**","authc");//所有的请求都需要认证
        filterchains.put("/common/**","anon");
        filterchains.put("/css/**","anon");
        filterchains.put("/webjars/**","anon");
        filterchains.put("/login","anon");

        shiroFilterFactoryBean.setLoginUrl("/login");//认证失败跳转的路径-->登陆页面

        return  shiroFilterFactoryBean;
    }
    //realm
    @Bean
    public SmbmsRealm smbmsRealm(){
        SmbmsRealm smbmsRealm = new SmbmsRealm();
        //数据   根据用户编码 查询user
        smbmsRealm.setUserService(userService);
        smbmsRealm.setPermissionService(permissionService);
        //指向凭证
        smbmsRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        return smbmsRealm;
    }
    //认证凭证器
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher(){
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        //算法
        hashedCredentialsMatcher.setHashAlgorithmName("md5");
        //散列次数
        hashedCredentialsMatcher.setHashIterations(1);
        return hashedCredentialsMatcher;
    }
}
